#pragma once

#include <iostream>
#include <string>
#include <cstring>
#include <pthread.h>
#include <unistd.h>
#include <functional>
#include "log.hpp"

namespace ephemerals
{
    using namespace LogModule;
    static uint32_t num = 0;

    class Thread
    {
        typedef std::function<void()> func_t;
    public:
        Thread(func_t func)
            :_isdetach(false)
            , _isrunning(false)
            , _tid(0)
            , _ret(nullptr)
            , _func(func)
        {
            _name = "thread_" + std::to_string(num++);
        }

        const std::string& name()
        {
            return _name;
        }

        bool Start()
        {
            if(_isrunning) return false;
            
            //将this传入静态成员函数，就能实现根据对象调用子方法
            int n = pthread_create(&_tid, nullptr, Routine, this);
            if(n != 0)
            {
                std::cerr << "pthread_create:" << strerror(n) << std::endl;
                return false;
            }
            
            if(_isdetach) pthread_detach(_tid);
            return true;
        }

        bool Stop()
        {
            if(_isrunning)
            {
                int n = pthread_cancel(_tid);
                if(n != 0)
                {
                    std::cerr << "pthread_cancel:" << strerror(n) << std::endl;
                    return false;
                }
                _isrunning = false;
                return true;
            }
            return false;
        }

        void Detach()
        {
            _isdetach = true;
            if(_isrunning) pthread_detach(_tid);
        }

        void Join()
        {
            if(_isdetach) return;
            int n = pthread_join(_tid, &_ret);
            if(n != 0)
            {
                std::cerr << "pthread_join:" << strerror(n) << std::endl;
                return;
            }
        }
    private:
        //普通成员函数有this指针，不能和线程对应的函数相匹配
        //所以要一个静态成员函数，args传入对应的对象地址
        //将this传入静态成员函数，就能实现根据对象调用子方法
        static void* Routine(void* args)
        {
            Thread* self = static_cast<Thread*>(args);
            self->_isrunning = true;
            pthread_setname_np(self->_tid, self->_name.c_str());
            self->_func();
            return nullptr;
        }

        bool _isdetach;
        bool _isrunning;
        std::string _name;
        pthread_t _tid;
        void* _ret;
        func_t _func;
    };
}